﻿using RabbitMQ.Client;
using Server;
using System;
using System.Text;

namespace SubscribePorducer
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine($@"发布/订阅模式----------------生产者---------------");
            var msg = "";
            do
            {
                Console.WriteLine("输入你要发送的消息：");
                msg = Console.ReadLine(); ;
                Producer.SendQueueMsg(msg);

            } while (msg.ToLower() != "out");
        }
    }


    class Producer
    {
        private static readonly ConnectionFactory rabbitMqFactory = CommonConnectionFactory.rabbitMqFactory;

        public static void SendQueueMsg(string msg = "0")
        {
            string ExchangeName = "订阅交换机";
            using (IConnection conn = rabbitMqFactory.CreateConnection())
            {
                using (IModel channel = conn.CreateModel())
                {

                    //direct：默认，根据routingKey完全匹配，好处是先匹配再发送
                    //topic：根据绑定关键字通配符规则匹配、比较灵活
                    //Fanout：不需要指定routingkey，相当于群发
                    //header：不太常用，可以自定义匹配规则
                    //声明交换机

                    channel.ExchangeDeclare(ExchangeName, ExchangeType.Fanout);
                  
                    for (int i = 0; i < 10; i++)
                    {
                        var msgBody = Encoding.UTF8.GetBytes($@"-{msg}{i.ToString()}-");
                        Console.WriteLine($@"=================={msgBody}===============");
                        //直接发送到交换机，但交换机本身不存储内容，消息数据存在队列中
                        channel.BasicPublish(exchange: ExchangeName,routingKey: "",basicProperties: null,body: msgBody);
                    }
                    channel.Close();
                }
            }
        }
    }
}
